package edu.umassd.visual.options;

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.BufferedWriter;
import java.io.IOException;
import java.nio.charset.Charset;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.StandardOpenOption;

import javax.swing.JFileChooser;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import edu.umassd.visual.DataPoints;

/**
 * Saves the provided dataset somewhere.
 * 
 * @author Dan Avila
 * 
 */
@Component
public class Save implements ActionListener
{
	@Autowired
	private DataPoints points;

	@Override
	public void actionPerformed(ActionEvent e)
	{
		JFileChooser chooser = new JFileChooser("./");
		chooser.setFileSelectionMode(JFileChooser.FILES_ONLY);

		int value = chooser.showSaveDialog(null);

		if (value == JFileChooser.APPROVE_OPTION)
		{
			Path p = chooser.getSelectedFile().toPath();

			try
			{
				StandardOpenOption[] ops =
				{ StandardOpenOption.CREATE_NEW };

				BufferedWriter writer = Files.newBufferedWriter(p,
						Charset.defaultCharset(), ops);

				writer.write(points.toString());

				writer.flush();
				writer.close();
			}
			catch (IOException e1)
			{
				e1.printStackTrace();
			}
		}
	}
}
